import { createRouter, createWebHashHistory } from 'vue-router'
import Auth from '@/views/AuthView.vue'
import HomeView from '@/views/HomeView.vue'

import MySpace from '@/components/MySpace/MySpace.vue'
import login from '@/components/Login/Login.vue'
import register from '@/components/Register/Register.vue'

import cookies from 'vue-cookies'

const routes = [
  {
    path:'/',
    redirect:'/auth/login'
  },
 
  {
    path: '/auth',
    name: 'Auth',
    component: Auth,
    children:[
      {
        path:"login",
        component:login
      },
      {
        path:"register",
        component:register
      }
  ]
  },

  {
    path: '/home',
    name: 'Home',
    component: HomeView,
    children:[
      {
        path:"space",
        component: MySpace
      }
    ]
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
  
})

// 路由守护
router.beforeEach((to,from,next)=>{

  let token=cookies.get("Authorization")
  //处理登录注册
  if((to.path === "/auth/login" || to.path === "/auth/register") && token != null){
    
    next({path:'/home'})
    
  }else  if((to.path === "/auth/login" || to.path === "/auth/register") && token == null){
    
    next()
  }
  
  else if(token != null){
    //未匹配到路由
    if (to.matched.length === 0) {  //如果未匹配到路由
      from.path? next({ path:from.path}) : next('/home');   //如果上级也未匹配到路由则跳转主页面，如果上级能匹配到则转上级路由
    } else {
      next();    //如果匹配到正确跳转
    } 
  }
  else if(token == null){
    next({path:'/auth/login'})
  }

})



export default router
